package com.itxiaowu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itxiaowu.constant.MessageConstant;
import com.itxiaowu.constant.RedisMessageConstant;
import com.itxiaowu.entity.Result;
import com.itxiaowu.pojo.Member;
import com.itxiaowu.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *  会员处理
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    /**
     *  处理登陆逻辑
     */
    @RequestMapping("/login.do")
    public Result login(HttpServletResponse response, @RequestBody Map map){

        String telephone = String.valueOf(map.get("telephone"));

        // 1: 先进性验证码比较
            // 拿去redis缓存中的数据
        Jedis jedis = jedisPool.getResource();
        String codeRedis = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        String validateCode = String.valueOf(map.get("validateCode"));

        if(codeRedis == null || !validateCode.equals(codeRedis)){
            // 没有数据 获得不相等
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        // 2: 查询数据库是否是会员, 不是则进行注册
        Member member = memberService.findByTelephone(telephone);

        if(member == null){
            // 没有注册, 进行会员注册
            member = new Member();
            member.setPhoneNumber(telephone);
            memberService.addMember(member);
        }

        // 3: 将数据封装到cookie中返回给浏览器
            // 跟踪会员
        Cookie cookie = new Cookie("login_member_telephone", telephone);
            // 设置cookie 路线
        cookie.setPath("/");
            // 设置cookie有效时间
        cookie.setMaxAge(60 * 3);
            // 写回给浏览器
        response.addCookie(cookie);

        // 3.5 : 保存会员信息到redis中
        String msg = JSON.toJSON(member).toString();
        jedis.setex(telephone,60 * 30, msg);

        jedis.close();

        // 4: 返回结果
        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }

}
